(function(window, $) {
	/** 回填表单数据 * */
	$.fn.fillJson = function(json) {
		for (var name in json) {
			var input = this.find('[name=' + name + ']');
			var value = json[name];
			var type = input.attr('type');
			if (input.is(':radio')) {
				this.find('[name=' + name + '][value=' + value + ']').prop(
						'checked', true);
			} else if (input.is(':checkbox')) {
				this.find('[name=' + name + '][value=' + value + ']').prop(
						'checked', true);
			} else {
				if (input.attr('dateformat')) {
					input
							.val(new Date(value).pattern(input
									.attr('dateformat')));
				} else {
					input.val(value);
				}
			}
		}
	};
	/** 获取表单要提交的数据对象 * */
	$.fn.serializeJson = function() {
		var data = this.serializeArray();
		var newdata = {};
		for (var i = 0; i < data.length; i++) {
			if (newdata[data[i].name] == undefined) {
				newdata[data[i].name] = data[i].value;
			} else {
				if (typeof(newdata[data[i].name]) != 'object') {
					var tv = newdata[data[i].name];
					newdata[data[i].name] = [];
					newdata[data[i].name].push(tv);
				}
				newdata[data[i].name].push(data[i].value);
			}
		}
		return newdata;
	};
	/**
	 * 格式化显示当前日期
	 */
	Date.prototype.pattern = function(fmt) {
		var o = {
			"M+" : this.getMonth() + 1, // 月份
			"d+" : this.getDate(), // 日
			"h+" : this.getHours(), // 小时
			"H+" : this.getHours(), // 小时
			"m+" : this.getMinutes(), // 分
			"s+" : this.getSeconds(), // 秒
			"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
			"S" : this.getMilliseconds()
			// 毫秒
		};
		var week = {
			"0" : "/u65e5",
			"1" : "/u4e00",
			"2" : "/u4e8c",
			"3" : "/u4e09",
			"4" : "/u56db",
			"5" : "/u4e94",
			"6" : "/u516d"
		};
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4
							- RegExp.$1.length));
		}
		if (/(E+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1,
					((RegExp.$1.length > 1) ? (RegExp.$1.length > 2
							? "/u661f/u671f"
							: "/u5468") : "")
							+ week[this.getDay() + ""]);
		}
		for (var k in o) {
			if (new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1)
								? (o[k])
								: (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;
	};
	$.ajaxSetup({
		beforeSend : function() {
			window.Pace && Pace.restart();
		},
		// cache: false,
		contentType : "application/x-www-form-urlencoded;charset=utf-8",
		complete : function(XMLHttpRequest, textStatus) {
            window.Pace && Pace.stop();
		},
		error : function(x, textStatus, errorThrown) {
			if (this.statusCode[x.status] == undefined) {
				base.top().toastr.error('请求发生了一点点意外，请稍后再试！');
			}
		},
		statusCode : {
			0 : function(e, state) {
				if (state != 'abort')
					base.top().toastr.warning('请求超时,服务器未响应！');
			},
			400 : function() {
				base.top().toastr.error('请求参数错误！');
			},
			401 : function() {
				top.base.lockLogin();
			},
			403 : function() {
				base.top().toastr.warning('您没有权限执行此项操作！');
			},
			408 : function() {
				base.top().layer.msg('请求超时，您的网络可能已经中断！', {
							icon : 5
						});
			},
			404 : function() {
				base.top().toastr.error('您当前的请求不存在！');
			},
			500 : function() {
				base.top().toastr.warning('请求发生了一点点意外，请稍后再试！');
			},
			503 : function() {
				base.top().toastr.warning('服务器繁忙，请稍后再试！');
			}
		}
	});
	var base = function() {
	};
	base.root = function() {
		return window.root ? window.root : '';
	}
	base.isXs = function() {
		return $(window).width() < 768;
	};
	base.page = function(selector, option, form) {
		var queryParams = function(params) {
			var data = $(form).serializeJson();
			$.extend(data, params)
			return data;
		};
		var df = {
			method : 'post',
			contentType : "application/x-www-form-urlencoded;charset=utf-8",
			cache : false,
			striped : true,
			pagination : true,
			showToggle : base.isXs(),
			cardView : base.isXs(),
			pageNumber : 1,
			pageSize : 10,
			pageList : [10, 20, 30, 50, 100],
			queryParams : queryParams, // 传递参数（*）
			sidePagination : "server", // 服务端请求
			queryParamsType : "undefined",
			clickToSelect : true,
			onPostBody : base.autoSize,
			columns : []
		};

		var setting = $.extend(df, option);
		$(selector).bootstrapTable('destroy').bootstrapTable(setting)
	};
	base.bindError = function(errors) {
		var df = {
			errors : [],
			selector : 'form'
		};
		if (errors instanceof Array) {
			df.errors = errors;
		} else {
			df = $.extend(df, errors);
		}
		var bv = $('form').data('bootstrapValidator');
        $(df.errors).each(function (i, _this) {
            bv.updateMessage(_this.name, 'blank', _this.message);
            bv.updateStatus(_this.name, 'INVALID', 'blank');
            toastr.error(_this.message);
        });
		$(df.selector).find('.error[name]:first').focus();
	};
	base.param = function(str) {
		if (!str) {
			str = location.search;
		}
		str = str.replace(/^\?/, '')
		var param = {};
		if (str == '') {
			return param;
		}
		$(str.split('&')).each(function(index, args) {
					var exp = args.split('=');
					param[exp[0]] = exp[1] ? decodeURIComponent(exp[1]) : '';
				});
		return param;
	};
	base.refresh = function() {
		location.reload();
	}
	var _loginLayer;
	base.lockLogin = function() {
		_loginLayer = layer.open({
			closeBtn : false,
			type : 2,
			title : false,
			shade : 0.3,
			area : ['320px', '405px'],
			resize : false,
			content : base.root() + '/login.do'
		});
	};
	base.loginBack = function() {
		if (_loginLayer) {
			layer.close(_loginLayer);
			delete _loginLayer;
			return true;
		} else {
			return false;
		}
	};
	base.replaceValue = function(tpl, data) {
		return tpl.replace(/#\{(.*?)\}/g, function(str, key) {
					return data[key];
				});
	}
	base.resetFrameSize = function(name) {
		var $iframe = $('iframe[name=' + name + ']');
		$iframe.height($iframe.contents().find('html').height() + 20);// 加20处理360浏览器下有时候窗口闪烁问题
		base.autoSize();
	};
	base.autoSize = function(force) {
		var name = window.name;
		if (name == '' || self == parent || !parent.base) {
			return;
		}
		if ((/^layui\-layer\-iframe\d*/.test(name) || $('body').is('[fixed]'))
				&& force != true) {
			return;
		}
		parent.base.resetFrameSize(name);
	};
	base.back = function() {// 如果使用history对象返回前页，会在整个页面（所有iframe）中响应
		location.href = document.referrer;
	};
	base.ajaxBack = function(rs, cb) {
		if (rs.success) {
			toastr.success(rs.message || '操作成功');
			if (typeof(cb) == 'function') {
				cb();
			}
		} else {
			toastr.error(rs.message || '操作失败');
			base.bindError(rs.errors);
		}
	};
	base.top = function() {
		return window.top;
	};
	base.open = function(settings, minW, minH) {
		var minW = minW ? minW : 420, minH = minH ? minH : 620,
		    w = $(window).width() * 0.8, h = $(window).height() * 0.8;
		w = w < minW ? $(window).width() : w;
		h = h < minH ? $(window).height() : h;
		var option = $.extend({
			type : 2,
			maxmin : true,
			area : [w + 'px', h + 'px']
		}, settings);
		layer.open(option);
	};
	base.tableColOpt = function(value, row, index, field) {
		var edit = '<a href="edit?id=' + value + '" class="btn btn-primary btn-sm"><i class="fa fa-edit"></i> 修改</a>',
		remove = '<button type="button" onclick="base.tableRowRemove(this,\'' + value + '\')" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i> 删除</button>';
		return [edit, remove].join(' ');
	};
	base.tableColDateTime = function(value, row, index, field) {
		if (value) {
			return new Date(value).pattern('yyyy-MM-dd HH:mm:ss');
		} else {
			return '';
		}
	};
	base.tableRowRemove = function(_this, id) {
		var ids = [], msg, $table, idField;
		if (id) {
            $table = $(_this).closest('[l-table]');
            idField = $table.data('idField')||'id';
			ids.push({name:idField, value: id});
			msg = '确定要删除当前记录吗？';
		} else {
			$table = $($(this).data('table'));
            idField = $table.data('idField')||'id';
			var list = $table.bootstrapTable('getSelections');
			for (var i = 0; i < list.length; i++) {
				ids.push({name:idField, value: list[i][idField]});
			}
			msg = '确定要删除所选记录吗？';
		}
		if (ids.length == 0) {
			base.top().toastr.error('请选择要删除的记录！');
			return false;
		}
        var url = $(this).data('url') || 'remove';
		bootbox.confirm(msg, function(res){
			if(!res){
				return;
			}
			$.post(url, ids, function(rs){
				base.ajaxBack(rs, function(){
					$table.bootstrapTable('refresh');
				});
			});
		});
		return false;
	}
    base.tableRowModify = function() {
        var ids = [], msg, $table = $($(this).data('table')),
            idField = $table.data('idField')||'id',
            list = $table.bootstrapTable('getSelections');
        if(list.length == 0){
        	base.top().toastr.error('请选择要编辑的记录！');
        	return;
        }
        if(list.length > 1){
            base.top().toastr.error('每次只能编辑一条记录！');
            return;
        }
        var url = $(this).data('url') || 'edit';
        location.href = url + '?'+idField+'=' + list[0][idField];
    }
	window.base = base;
	$.fn.baseCheckbox = function() {
		var selector = this.data('selector');
		var _this = this;
		$(this).click(function() {
					$(selector).prop('checked', _this.prop('checked'));
				});
		$(selector).click(function() {
			var length = $(selector).filter(':not(:checked)').length
			if (length > 0 && _this.prop('checked')) {
				_this.prop('checked', false);
			} else if (length == 0 && !_this.prop('checked')) {
				_this.prop('checked', true);
			}
		});
	}
	$(function() {
		if (window.toastr) {
			toastr.options = {
				progressBar : true,
				positionClass : 'toast-bottom-right'
			}
		}
		$('[data-provide="baseCheckbox"]').baseCheckbox();
        $('#logout').click(function () {
            layer.confirm('确定要退出系统吗？', function () {
                location.href = base.root() + '/logout.do';
            });
        });
		$('#to-changepwd').click(function() {
			layer.open({
						type : 2,
						title : '修改密码',
						shade : 0.3,
						area : ['320px', '390px'],
						resize : false,
						content : base.root()
								+ '/admin/usercenter/changepwd.do'
					});
		});
		// base.autoSize();
		// $(window).resize(base.autoSize);
		if (window.layer) {
			layer.config({
						success : base.autoSize,
						end : base.autoSize
					});
		}
		// $('[data-widget=collapse]').click(function() {
		// var $this = $(this), $i = $this.children(), $box = $this
		// .parents('.box:first')
		// .children(':not(.box-header)');
		// if ($i.is('.fa-minus')) {
		// $i.removeClass('fa-minus').addClass('fa-plus');
		// $box.slideUp(800, base.autoSize);
		// } else {
		// $i.removeClass('fa-plus').addClass('fa-minus');
		// $box.slideDown(800, base.autoSize);
		// }
		// });
		$.fn.iCheck && $('[l-icheck]').iCheck({
					checkboxClass : 'icheckbox_square-blue',
					radioClass : 'iradio_square-blue'
				});
		$.fn.bootstrapValidator && $('[l-bv]').bootstrapValidator({
			feedbackIcons : {
				valid : 'fa fa-check',
				invalid : 'fa fa-remove',
				validating : 'fa fa-refresh'
			}
		}).on('success.form.bv', function(e) {
			e.preventDefault();
			var $form = $(e.target);
			$.ajax({
				url : $form.attr('action') || '',
				type : $form.attr('method') || 'post',
				dataType : 'json',
				data : $form.serialize(),
				success : function(rs){
					base.ajaxBack(rs, function(){
					   $form.find('[name=id]').val(rs.data.id);
					});
				}
			});
		});
        $.fn.bootstrapTable && $('[l-table]').each(function () {
            var $this = $(this);
            base.page($this, {}, $this.attr('l-table-form'));
            $($this.attr('l-table-form')).submit(function () {
                base.page($this, {}, $this.attr('l-table-form'));
            });
        });
		$('[l-modify]').click(base.tableRowModify);
		$('[l-remove]').click(base.tableRowRemove);

        $.fn.select2 && $.fn.select2.defaults.set("language", "zh-CN");
        $.fn.select2 && $('[l-select2]').select2();
    });
    
    var list = $('#leftMenu').find('a');
    for (var i = 0; i < list.length; i++) {
        var url = $(list[i]).attr('href');
        if(location.pathname.startsWith(url)){
            $(list[i]).parentsUntil('#leftMenu', 'li').addClass('active menu-open');
            break;
        }
    }
})(this, jQuery);